﻿using Newtonsoft.Json.Linq;
using SDWXServer.KD;
using SDWXServer.Models;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.CO2NET.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SDWXServer.Controllers
{
    /// <summary>
    /// 公众号
    /// </summary>
    public class MPController : ApiController
    {
        //与微信公众账号后台的Token设置保持一致，区分大小写。
        public static readonly string Token = Senparc.Weixin.Config.SenparcWeixinSetting.Token;
        //与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static readonly string EncodingAESKey = Senparc.Weixin.Config.SenparcWeixinSetting.EncodingAESKey;
        //与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static readonly string AppId = Senparc.Weixin.Config.SenparcWeixinSetting.WeixinAppId;


        /// <summary>
        /// 认证接口
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        public HttpResponseMessage Get(string signature, string timestamp, string nonce, string echostr)
        {
            var checkResult = "";
            if (CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                checkResult = echostr; //返回随机字符串则表示验证通过
            }
            else
            {
                checkResult = "failed:" + signature + "," + Senparc.Weixin.MP.CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                    "如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。";
            }

            var result = new StringContent(echostr, UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
            var response = new HttpResponseMessage { Content = result };
            return response;
        }
        /// <summary>
        /// 消息接收
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage Post()
        {
            var postModel = new PostModel();
            postModel.Token = Token;
            postModel.EncodingAESKey = EncodingAESKey;
            postModel.AppId = AppId;

            //v4.2.2之后的版本，可以设置每个人上下文消息储存的最大数量，防止内存占用过多，如果该参数小于等于0，则不限制
            var maxRecordCount = 10;

            try
            {
                //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
                var messageHandler = new WRZSMessageHandler(HttpContext.Current.Request.InputStream, postModel, maxRecordCount);

                #region 设置消息去重
                /* 如果需要添加消息去重功能，只需打开OmitRepeatedMessage功能，SDK会自动处理。
                 * 收到重复消息通常是因为微信服务器没有及时收到响应，会持续发送2-5条不等的相同内容的RequestMessage*/
                messageHandler.OmitRepeatedMessage = true;//默认已经开启，此处仅作为演示，也可以设置为false在本次请求中停用此功能
                #endregion

                //记录 Request 日志（可选）
                //messageHandler.SaveRequestMessageLog();
                //执行微信处理过程（关键）
                messageHandler.Execute();
                //记录 Response 日志（可选）
                //messageHandler.SaveResponseMessageLog();

                var responseContent = messageHandler.ResponseDocument.ToString();
                return new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(responseContent, Encoding.UTF8, "application/xml"),
                };
            }
            catch (Exception ex)
            {
                #region 异常处理
                Senparc.Weixin.WeixinTrace.Log("MessageHandler错误：{0}", ex.Message);

                var responseContent = ex.Message;
                return new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(responseContent, Encoding.UTF8, "application/x-www-form-urlencoded"),
                };

                #endregion
            }
        }
    }
}